{% extends 'base/base.html' %}
{% load static %}
{% load i18n %}

{% block title %}{% trans "消息管理" %} - {{ project.name }}{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-0">
                <i class="fa fa-envelope"></i>
                {% trans "消息管理" %}
            </h1>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{% url 'projects:dashboard' %}">{% trans "仪表盘" %}</a></li>
                    <li class="breadcrumb-item"><a href="{% url 'projects:project_detail' project.id %}">{{ project.name }}</a></li>
                    <li class="breadcrumb-item active">{% trans "消息管理" %}</li>
                </ol>
            </nav>
        </div>
        <div>
            <a href="{% url 'projects:project_detail' project.id %}" class="btn btn-outline-secondary">
                <i class="fa fa-arrow-left"></i>
                {% trans "返回项目" %}
            </a>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card bg-primary text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h5 class="card-title">{% trans "总消息" %}</h5>
                            <h2 class="mb-0">{{ page_obj.paginator.count }}</h2>
                        </div>
                        <div class="align-self-center">
                            <i class="fa fa-envelope fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-warning text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h5 class="card-title">{% trans "未处理" %}</h5>
                            <h2 class="mb-0">{{ pending_count }}</h2>
                        </div>
                        <div class="align-self-center">
                            <i class="fa fa-clock-o fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h5 class="card-title">{% trans "已处理" %}</h5>
                            <h2 class="mb-0">{{ processed_count }}</h2>
                        </div>
                        <div class="align-self-center">
                            <i class="fa fa-check-circle fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-info text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h5 class="card-title">{% trans "Webhook" %}</h5>
                            <h2 class="mb-0">{{ webhook_count }}</h2>
                        </div>
                        <div class="align-self-center">
                            <i class="fa fa-bell fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 筛选和工具栏 -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="get" class="row g-3">
                <div class="col-md-4">
                    <label class="form-label">{% trans "消息类型" %}</label>
                    <select name="type" class="form-select">
                        <option value="">{% trans "全部类型" %}</option>
                        <option value="announcement" {% if message_type == 'announcement' %}selected{% endif %}>{% trans "公告消息" %}</option>
                        <option value="webhook" {% if message_type == 'webhook' %}selected{% endif %}>{% trans "Webhook消息" %}</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label">{% trans "处理状态" %}</label>
                    <select name="status" class="form-select">
                        <option value="">{% trans "全部状态" %}</option>
                        <option value="pending" {% if status == 'pending' %}selected{% endif %}>{% trans "未处理" %}</option>
                        <option value="processed" {% if status == 'processed' %}selected{% endif %}>{% trans "已处理" %}</option>
                    </select>
                </div>
                <div class="col-md-4 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary me-2">
                        <i class="fa fa-filter"></i>
                        {% trans "筛选" %}
                    </button>
                    <a href="{% url 'projects:message_list' project.id %}" class="btn btn-secondary">
                        <i class="fa fa-refresh"></i>
                        {% trans "重置" %}
                    </a>
                </div>
            </form>
        </div>
    </div>

    <!-- 批量操作 -->
    {% if user.is_super_admin or user_role == 'admin' %}
        <div class="card mb-4">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <button type="button" class="btn btn-outline-success" id="mark-processed-btn">
                            <i class="fa fa-check"></i>
                            {% trans "标记为已处理" %}
                        </button>
                        {% if user.is_super_admin or user_role == 'admin' %}
                            <button type="button" class="btn btn-outline-warning" id="mark-pending-btn">
                                <i class="fa fa-clock-o"></i>
                                {% trans "标记为未处理" %}
                            </button>
                        {% endif %}
                    </div>
                    <div>
                        <span id="selected-count" class="text-muted">{% trans "已选择" %} 0 {% trans "条消息" %}</span>
                    </div>
                </div>
            </div>
        </div>
    {% endif %}

    <!-- 消息列表 -->
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0">{% trans "消息列表" %}</h5>
        </div>
        <div class="card-body p-0">
            {% if page_obj.object_list %}
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th width="40">
                                    <input type="checkbox" id="select-all" class="form-check-input">
                                </th>
                                <th>{% trans "类型" %}</th>
                                <th>{% trans "标题" %}</th>
                                <th>{% trans "内容" %}</th>
                                <th>{% trans "状态" %}</th>
                                <th>{% trans "创建时间" %}</th>
                                <th>{% trans "处理人" %}</th>
                                <th>{% trans "操作" %}</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for message in page_obj.object_list %}
                                <tr data-message-id="{{ message.id }}">
                                    <td>
                                        <input type="checkbox" class="message-checkbox form-check-input" value="{{ message.id }}">
                                    </td>
                                    <td>
                                        {% if message.message_type == 'announcement' %}
                                            <span class="badge bg-primary">
                                                <i class="fa fa-bullhorn"></i>
                                                {% trans "公告" %}
                                            </span>
                                        {% else %}
                                            <span class="badge bg-info">
                                                <i class="fa fa-bell"></i>
                                                {% trans "Webhook" %}
                                            </span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <strong>{{ message.title|truncatechars:50 }}</strong>
                                    </td>
                                    <td>
                                        <span class="text-muted">{{ message.content|truncatechars:100 }}</span>
                                    </td>
                                    <td>
                                        {% if message.is_processed %}
                                            <span class="badge bg-success">
                                                <i class="fa fa-check-circle"></i>
                                                {% trans "已处理" %}
                                            </span>
                                        {% else %}
                                            <span class="badge bg-warning text-dark">
                                                <i class="fa fa-clock-o"></i>
                                                {% trans "未处理" %}
                                            </span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <small class="text-muted">
                                            <i class="fa fa-clock"></i>
                                            {{ message.created_at|date:"Y-m-d H:i" }}
                                        </small>
                                    </td>
                                    <td>
                                        {% if message.processed_by %}
                                            <small class="text-muted">
                                                <i class="fa fa-user"></i>
                                                {{ message.processed_by.username }}
                                            </small>
                                        {% else %}
                                            <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td class="td-actions">
                                        <div class="d-flex gap-1">
                                            <a href="{% url 'projects:message_detail' project.id message.id %}" class="btn btn-sm btn-outline-primary" title="{% trans "查看详情" %}">
                                                <i class="fa fa-eye"></i>
                                                <span class="ms-1">{% trans "详情" %}</span>
                                            </a>
                                            {% if user.is_super_admin or user_role == 'admin' %}
                                                {% if message.is_pending %}
                                                    <button type="button" class="btn btn-sm btn-outline-success mark-processed-btn" data-id="{{ message.id }}" title="{% trans "标记为已处理" %}">
                                                    <i class="fa fa-check"></i>
                                                    <span class="ms-1">{% trans "处理" %}</span>
                                                </button>
                                                {% else %}
                                    {% if user.is_super_admin or user_role == 'admin' %}
                                        <button type="button" class="btn btn-sm btn-outline-warning mark-pending-btn" data-id="{{ message.id }}" title="{% trans "标记为未处理" %}">
                                            <i class="fa fa-clock-o"></i>
                                            <span class="ms-1">{% trans "撤销" %}</span>
                                        </button>
                                    {% endif %}
                                                {% endif %}
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            {% else %}
                <div class="text-center py-5">
                    <i class="fa fa-envelope fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted">{% trans "暂无消息" %}</h5>
                    <p class="text-muted">{% trans "当前项目还没有收到任何消息" %}</p>
                </div>
            {% endif %}
        </div>
        {% if page_obj.has_other_pages %}
            <div class="card-footer">
                <nav aria-label="Page navigation">
                    <ul class="pagination justify-content-center mb-0">
                        {% if page_obj.has_previous %}
                            <li class="page-item">
                                <a class="page-link" href="?page=1{% if message_type %}&type={{ message_type }}{% endif %}{% if status %}&status={{ status }}{% endif %}">{% trans "首页" %}</a>
                            </li>
                            <li class="page-item">
                                <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if message_type %}&type={{ message_type }}{% endif %}{% if status %}&status={{ status }}{% endif %}">{% trans "上一页" %}</a>
                            </li>
                        {% endif %}
                        
                        {% for num in page_obj.paginator.page_range %}
                            {% if page_obj.number == num %}
                                <li class="page-item active">
                                    <span class="page-link">{{ num }}</span>
                                </li>
                            {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                                <li class="page-item">
                                    <a class="page-link" href="?page={{ num }}{% if message_type %}&type={{ message_type }}{% endif %}{% if status %}&status={{ status }}{% endif %}">{{ num }}</a>
                                </li>
                            {% endif %}
                        {% endfor %}
                        
                        {% if page_obj.has_next %}
                            <li class="page-item">
                                <a class="page-link" href="?page={{ page_obj.next_page_number }}{% if message_type %}&type={{ message_type }}{% endif %}{% if status %}&status={{ status }}{% endif %}">{% trans "下一页" %}</a>
                            </li>
                            <li class="page-item">
                                <a class="page-link" href="?page={{ page_obj.paginator.num_pages }}{% if message_type %}&type={{ message_type }}{% endif %}{% if status %}&status={{ status }}{% endif %}">{% trans "末页" %}</a>
                            </li>
                        {% endif %}
                    </ul>
                </nav>
            </div>
        {% endif %}
    </div>
</div>

<style>
    .td-actions {
        white-space: nowrap;
    }
    
    .card {
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }
    
    .card-header {
        background-color: #f8f9fa;
        border-bottom: 1px solid #dee2e6;
    }
    
    .badge {
        font-size: 0.75em;
    }
</style>

<script>
// 获取CSRF token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 获取CSRF token（优先从meta标签获取）
function getCSRFToken() {
    const meta = document.querySelector('meta[name="csrf-token"]');
    if (meta) {
        return meta.getAttribute('content');
    }
    return getCookie('csrftoken');
}

document.addEventListener('DOMContentLoaded', function() {
    const selectAllCheckbox = document.getElementById('select-all');
    const messageCheckboxes = document.querySelectorAll('.message-checkbox');
    const selectedCountSpan = document.getElementById('selected-count');
    const markProcessedBtn = document.getElementById('mark-processed-btn');
    const markPendingBtn = document.getElementById('mark-pending-btn');
    
    // 更新选中计数和按钮状态
    function updateSelectionState() {
        const selectedCount = document.querySelectorAll('.message-checkbox:checked').length;
        selectedCountSpan.textContent = `已选择 ${selectedCount} 条消息`;
        markProcessedBtn.disabled = selectedCount === 0;
        markPendingBtn.disabled = selectedCount === 0;
    }
    
    // 全选/取消全选
    selectAllCheckbox.addEventListener('change', function() {
        messageCheckboxes.forEach(checkbox => {
            checkbox.checked = selectAllCheckbox.checked;
        });
        updateSelectionState();
    });
    
    // 单个复选框变化
    messageCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', updateSelectionState);
    });
    
    // 批量标记为已处理
    markProcessedBtn.addEventListener('click', function() {
        bulkUpdateMessages('mark_processed');
    });
    
    // 批量标记为未处理
    markPendingBtn.addEventListener('click', function() {
        bulkUpdateMessages('mark_pending');
    });
    
    // 单个消息状态切换
    document.querySelectorAll('.mark-processed-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const messageId = this.dataset.id;
            toggleMessageStatus(messageId, 'mark_processed');
        });
    });
    
    document.querySelectorAll('.mark-pending-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const messageId = this.dataset.id;
            toggleMessageStatus(messageId, 'mark_pending');
        });
    });
    
    // 切换单个消息状态
    function toggleMessageStatus(messageId, action) {
        const csrftoken = getCSRFToken();
        
        fetch('/{{ project.id }}/messages/' + messageId + '/toggle-status/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrftoken
            },
            body: JSON.stringify({ action: action })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                alert(data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('操作失败，请重试');
        });
    }
    
    // 批量更新消息状态
    function bulkUpdateMessages(action) {
        const selectedIds = Array.from(document.querySelectorAll('.message-checkbox:checked'))
            .map(checkbox => checkbox.value);
        
        if (selectedIds.length === 0) {
            alert('请选择要操作的消息');
            return;
        }
        
        const csrftoken = getCSRFToken();
        
        fetch('/{{ project.id }}/messages/bulk-update/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrftoken
            },
            body: JSON.stringify({
                message_ids: selectedIds,
                action: action
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                alert(data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('批量操作失败，请重试');
        });
    }
});
</script>
{% endblock %}